package com.to_door_recycle.user_wxapp.manager;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

@RestController
@RequestMapping("/wechat")
public class WechatManager {

    private static final String APP_ID = "wxa906c62033d7a84e";
    private static final String APP_SECRET = "4fa9c335bdfe12f237ca760c34cf5d14";

    @GetMapping("/sessionKey")
    public String getSessionKey(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String requestUrl = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("appid", APP_ID)
                .queryParam("secret", APP_SECRET)
                .queryParam("js_code", code)
                .queryParam("grant_type", "authorization_code")
                .toUriString();

        HttpResponse response = HttpUtil.createGet(requestUrl).execute();

        // 获取 session_key 和 openid
        JSONObject parseObj = JSONUtil.parseObj(response.body());

        String sessionKey = (String) parseObj.get("session_key");
        String openid = (String) parseObj.get("openid");
        System.out.println(sessionKey);
        System.out.println(openid);
        return sessionKey;
    }

    public String decryptPhoneNumber(String encryptedData, String iv, String sessionKey) throws Exception {
        byte[] dataByte = Base64.getDecoder().decode(encryptedData);
        byte[] keyByte = Base64.getDecoder().decode(sessionKey);
        byte[] ivByte = Base64.getDecoder().decode(iv);

        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, spec, new IvParameterSpec(ivByte));
        byte[] result = cipher.doFinal(dataByte);

        String resultStr = new String(result, "UTF-8");
        // 解析 JSON 字符串以获取手机号
        return parsePhoneNumber(resultStr);
    }

    private String parsePhoneNumber(String json) {
        // 解析 JSON，获取用户手机号
        return (String) JSONUtil.parseObj(json).get("phoneNumber");
    }

}
